class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int> > ret(n,vector<int>(n,0));
        int loop = n * n;
        int l = 0;
        int r = n - 1;
        int top = 0;
        int base = n - 1;
        int count = 1;
        
        while(loop--){
            for(int i = l;i <= r;i++){
                ret[top][i] = count++;
            }
            for(int i = top + 1;i <= base;i++){
                ret[i][r] = count++;
            }
            for(int i = r - 1;i >= l;i--){
                ret[base][i] = count++;
            }
            for(int i = base - 1;i > top;i--){
                ret[i][l] = count++;
            }
            l++;
            r--;
            top++;
            base--;
        }
        return ret;
    }
};
